package com.ma.imserver.netty.tcp;

import com.ma.imserver.netty.IMChannelHandler;
import com.ma.imserver.netty.IMServer;
import com.ma.imserver.netty.tcp.endecode.MessageProtocolDecoder;
import com.ma.imserver.netty.tcp.endecode.MessageProtocolEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "tcpsocket",value = "enable",havingValue = "true",matchIfMissing = false)
public class TcpSocketServer implements IMServer {
    private volatile boolean ready = false;
    @Value("${tcpsocket.port}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    @Override
    public boolean isReady() {
        return ready;
    }

    @Override
    public void stop() {
        if (bossGroup != null && !bossGroup.isShutdown() && !bossGroup.isShuttingDown()) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null && !workerGroup.isShutdown() && !workerGroup.isShuttingDown()) {
            workerGroup.shutdownGracefully();
        }
        this.ready = false;
        log.info("TcpSocketServer stopped");
    }

    @Override
    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        //设置为主从线程模型
        bootstrap.group(bossGroup, workerGroup)
                //设置为服务端NIO通信类型
                .channel(NioSctpServerChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    public void initChannel(Channel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new IdleStateHandler(120,0,0, TimeUnit.SECONDS));
                        pipeline.addLast("encode",new MessageProtocolEncoder());
                        pipeline.addLast("decode",new MessageProtocolDecoder());
                        pipeline.addLast("handler",new IMChannelHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG,5)
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        try {
            Channel channel = bootstrap.bind(port).sync().channel();
            //就绪标志
            this.ready = true;
            log.info("TcpSocketServer started,端口：{}",port);
            // channel.closeFuture().sync();
        }catch (Exception e){
            log.info("TcpSocketServer 初始化异常",e);
        }
    }
}
